package net.godcode.olivenotes.components;

import net.godcode.olivenotes.entities.Role;
import net.godcode.olivenotes.entities.RoleDAO;
import net.godcode.olivenotes.entities.User;
import net.godcode.olivenotes.entities.UserDAO;
import net.godcode.olivenotes.services.security.NoSuchUserException;
import net.godcode.olivenotes.services.security.PasswordMismatchException;
import net.godcode.olivenotes.services.security.UserAuthenticator;

import org.apache.tapestry.annotations.Component;
import org.apache.tapestry.annotations.Mixin;
import org.apache.tapestry.annotations.SetupRender;
import org.apache.tapestry.annotations.SupportsInformalParameters;
import org.apache.tapestry.corelib.components.ActionLink;
import org.apache.tapestry.corelib.components.Form;
import org.apache.tapestry.corelib.mixins.RenderInformals;
import org.apache.tapestry.ioc.annotations.Inject;
import org.slf4j.Logger;

@SupportsInformalParameters
/**
 * The login component provides a user login form as well as centralized
 * user authentication logic.
 * 
 * @author Chris Lewis Jan 2, 2008 <chris@thegodcode.net>
 * @version $Id: Login.java 20 2008-01-15 07:22:45Z burningodzilla $
 */
public class Login {
	
	@SuppressWarnings("unused")
	@Component(type = "form", id = "loginForm")
	private Form loginForm;
	
	@SuppressWarnings("unused")
	@Component(type = "actionlink", id = "logout")
	private ActionLink logoutLink;
	
	@SuppressWarnings("unused")
	@Mixin
	private RenderInformals renderInformals;
	
	@Inject
	private UserDAO userDao;
	
	@Inject
	private RoleDAO roleDao;
	
	@Inject
	private UserAuthenticator authenticator;
	
	@Inject
	private Logger log;
	
	private String userName;
	
	private String password;
	
	@SetupRender
	void onActivate() {
		//TODO test
		if(userDao.findByUserName("chrislewis") == null) {
			User _user = new User();
			_user.setUserName("chrislewis");
			_user.setFirstName("Chris");
			_user.setLastName("Lewis");
			_user.setEmailAddress("email");
			_user.setPassword("98f6bcd4621d373cade4e832627b4f6");//MD5 of 'test'
			_user.getRoles().add(roleDao.save(new Role("TESTROLE", "test")));
			userDao.save(_user);
		}
	}
	
	void onSuccessFromLoginForm() {
		try {
			authenticator.authenticate(userName, password);
		} catch(PasswordMismatchException pmmex) {
			log.error("TODO");
		} catch(NoSuchUserException nsuex) {
			log.error("TODO");
		}
	}
	
	void onActionFromLogout() {
		authenticator.logout();
	}
	
	/**
	 * @return the userName
	 */
	public String getUserName() {
		return userName;
	}

	/**
	 * @param userName the userName to set
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}
	
}
